<template>
  <div class="tw-ecoapplist">
    <div class="tw-ecoapplist-detail">
      <!-- 面包屑 -->
      <div class="tw-comcrm">
        <i class="tw-comcrm-svg"></i>
        <a class="tw-comcrm-text" style="margin-left: 10px">当前位置：</a>
        <a style="margin-left: 0" class="tw-comcrm-link" @click="back">应用列表</a>
        <span class="tw-comcrm-self">应用详情</span>
      </div>
      <!-- /面包屑面包屑 -->
      <div class="tw-ecoapplist-detail-content">
        <div class="tw-ecoapplist-detail-left">
          <img
            class="tw-ecoapplist-app-img ximg"
            v-if="appInfo.img || appInfo.icon1"
            :src="
              (appInfo.img || appInfo.icon1).startsWith('http')
                ? appInfo.img
                : `${fsBaseUrl || gateway}/fs/media${appInfo.img || appInfo.icon1}`
            "
            @error="imgError"
          />
          <img class="tw-ecoapplist-app-img ximg" v-else :src="defaultApp" />
          <div class="tw-ecoapplist-detail-desc">
            <div>
              <span>{{ appInfo.appName }}</span>
              <div>
                <!-- v-if="isDocMenu" -->
                <a class="isDocMenu" v-if="isDocMenu" @click="toDocument">帮助文档</a>

                <!-- <a class="twui-btn xborder twui-btncanel" -->
                <a class="twui-btn tw-btn-in-app" @click.stop="appEnter(appInfo, groupAppList)">进入应用</a>
              </div>
            </div>
            <ul>
              <li>
                <span>应用类型：</span>
                <span>{{ getOsTypeOptions(appInfo.type) }}</span>
              </li>
              <li>
                <span>适用学段：</span>
                <span>{{ formatSection(appInfo.sectionId) }}</span>
              </li>
              <li>
                <span>适用科目：</span>
                <span>{{ formatSubject(appInfo.subjectId) }}</span>
              </li>
              <li>
                <span>创建时间：</span>
                <span>{{ appInfo.createTime }}</span>
              </li>
              <li>
                <span>更新时间：</span>
                <span>{{ appInfo.lastmodifyTime }} </span>
              </li>
            </ul>
          </div>
        </div>

        <div class="tw-ecoapplist-detail-right" v-show="isPath">
          <div v-if="appInfo.domain">
            <div class="tw-ecoapplist-detail-right-border">
              <!-- <div id="qrCode" ref="qrCodeDiv"></div> -->
              <img :src="qrPath" width="150" height="150" />
              <!-- <QrcodeVue :value="qrPath" :size="150" level="L" :color-dark="'#333'" :color-light="'#fff'" /> -->
            </div>
            <div style="margin: 8px 0">
              <a class="showEwm" @click="showEwm('1')">点击重新生成二维码</a>
              <div style="margin-top: 4px">扫描二维码进入应用</div>
            </div>
          </div>
          <div v-else>暂无二维码</div>
        </div>
      </div>
      <div class="tw-ecoapplist-detail-center">
        <div class="tw-ecoapplist-detail-title xtitle">应用介绍</div>
        <div>{{ appInfo.description }}</div>
        <div class="tw-ecoapplist-detail-center-icon2" v-if="appInfo.icon2">
          <div v-for="(item, index) of appInfo.icon2.split(',')" :key="index">
            <img :src="`${fsBaseUrl || gateway}/fs/media${item}`" />
          </div>
        </div>
      </div>
      <div class="tw-ecoapplist-detail-bottom">
        <div class="tw-ecoapplist-detail-title xtitle">评论</div>
        <div class="tw-ecoapplist-detail-review" v-if="commentShow && appInfo.commentStatus === '1'">
          <textarea
            class="zd_textarea"
            placeholder="输入要发布的内容..."
            maxlength="150"
            v-model="commentAdd.appComment"
            name
            id
            cols="30"
            rows="10"
          ></textarea>
        </div>
        <div class="tw-ecoapplist-detail-review-contorl" v-if="commentShow">
          <div>
            <span>评分：</span>
            <el-rate :colors="['#FFB712', '#FFB712', '#FFB712', '#FFB712', '#FFB712']" v-model="commentAdd.score"></el-rate>
          </div>
          <el-button class="tw-btn-in-app" @click="commentHandAdd">发表</el-button>
        </div>
        <div class="tw-ecoapplist-detail-review-content">
          <ul>
            <li v-for="(item, index) in comments" :key="index">
              <div class="content-left">
                <img class="twm-avatar" src="./assets/user_default.png" />
              </div>
              <div class="content-right">
                <div>
                  <span>{{ item.userName }}</span>
                  <el-rate
                    :colors="['#FFB712', '#FFB712', '#FFB712', '#FFB712', '#FFB712']"
                    v-model="item.score"
                    disabled
                  ></el-rate>
                </div>
                <div>{{ item.appComment }}</div>
                <div>{{ item.createTime }}</div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<!-- <script setup>
import { ref } from "vue";
// import QrcodeVue from "qrcode.vue";
import axios from "@/utils/api/base";
import { openApp } from "@/utils/api/appcenter";
const fsBaseUrl = ref(window.$app.fsBaseUrl);
const gateway = ref(window.$app.gateway);
// const fileBaseUrl = ref(window.$app.fileBaseUrl);
</script> -->
<script>
// import props from "./props";
// import QRCode from "qrcodejs2";
// import nodata from "@/tw-lib-base/no-data/no-data";
import axios from "@/management/api/eco/base";
import QRCode from 'qrcode'
import { openApp } from "@/management/api/eco/appcenter";
import defaultApp from "./assets/app-default.png";

export default {
  name: "EcoAppDetail",
  data() {
    return {
      fsBaseUrl: "",
      gateway: "",
      qrPath: "",
      path: "",
      isPath: true,
      currentColor: ".currentColor",
      defaultApp,
      displayPlatformArr: [[""], ["pc"], ["mobile"], ["pc", "mobile"]],
      showappcate: false,
      appListCopy: [],
      paasName: "",
      preventReClick: true,
      showShadow: false,
      isDocMenu: false,
      commentShow: true,
      comments: [],
      commentAdd: {
        appComment: "",
        score: 0,
        appId: "",
        userId: ""
      },
      value1: "",
      appId: "",
      appInfo: "",
      collect_app_max_count: 10,
      otherAppName: "",
      otherAppPath: "",
      innerText: "",
      dialogVisible: false,
      currentApp: {},
      curOtherAppList: [],
      appDownload: {
        windowsX64downloadUrl: "",
        windowsX32downloadUrl: "",
        windowsXAlldownloadUrl: "",
        macAppdownloadUrl: "",
        linuxAppdownloadUrl: "",
        androidAppdownloadUrl: "",
        iosAppdownloadUrl: ""
      },
      isShowDownload: false,
      activeIndex: 0,
      seachText: "",
      btnEditeStatus: false,
      drag: false,
      downBtn: false,
      appcatesortList: [],
      groupAppList: [],
      appList: "",
      appAuthList: [],
      osTypeOptions: [
        {
          label: "教学应用",
          value: "1",
          color: "#94adff"
        },
        {
          label: "学习应用",
          value: "2",
          color: "#87a0c5"
        },
        {
          label: "管理应用",
          value: "3",
          color: "#679fff"
        },
        {
          label: "评价应用",
          value: "4",
          color: "#ff9640"
        },
        {
          label: "教研应用",
          value: "5",
          color: "#8787ff"
        },
        {
          label: "其他应用",
          value: "6",
          color: "#87a0c5"
        },
        {
          label: "资源应用",
          value: "7",
          color: "#ff8b6d"
        },
        {
          label: "课堂应用",
          value: "8",
          color: "#02a4f9"
        },
        {
          label: "授课工具",
          value: "9",
          color: "#878bff"
        }
      ],
      sectionList: [],
      appRecentVisit: [],
      authList: [],
      allAppList: [],
      delAppList: [],
      appList_show: false,
      appType: "4",
      appTime: 1000,
      ifDownloadUrl: true,
      numPerRow: 4,
      tipThirdPartyApp: false,
      isCate: true,
      scrollHeight: 90,
      appImages: [],
      webName: "ECO平台",
      documentUrl: "/dev/#/integrate/api/readme"
    };
  },
  computed: {
    displayPlatformFilter() {
      let index = 0;
      if (this.appType === "4") {
        index = 1;
      } else {
        index = Number(this.appType);
      }
      return this.displayPlatformArr[index];
    }
  },

  created() {
    this.fsBaseUrl = window.$app.fsBaseUrl || '';
    this.gateway = window.$app.gateway || '';
    this.appId = this.$route.query.appId; // this.getQueryString("appId");
    this.getAppDetails(this.appId);
  },

  methods: {
    imgError(e) {
      e.target.src = this.defaultApp;
    },
    deepClone(obj) {
      // 判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
      let objClone = Array.isArray(obj) ? [] : {};
      // 进行深拷贝的不能为空，并且是对象或者是
      if (obj && typeof obj === "object") {
        for (const key in obj) {
          // eslint-disable-next-line no-prototype-builtins
          if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === "object") {
              objClone[key] = this.deepClone(obj[key]);
            } else {
              objClone[key] = obj[key];
            }
          }
        }
      }
      return objClone;
    },

    back() {
      this.$router.push({
        name: "appcenter"
      });
    },
    getQueryString(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let r = (window.location.hash || window.location.search).substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    toDetails(item) {
      if (this.btnEditeStatus) return;
      window.location.hash = `appId=${item.id}`;
      this.appId = item.id;
      this.getAppDetails(this.appId);
    },
    queryAllTypeByLang() {
      const parmas = `Language=zh_CN`; // 'en-US' ? 'Language=en_US' : 'Language=zh_CN'
      this.axiosApi("/openapi-uc/appType/queryAllTypeByLang", parmas, "post", {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;"
        }
      }).then(res => {
        if (res.pageInfo && res.pageInfo.list && res.pageInfo.list.length >= 1) {
          const list = res.pageInfo.list.map(x => {
            return {
              value: x.appType,
              categoryId: x.appType,
              label: x.typeName,
              sortNum: x.sortNum || ""
            };
          });
          this.osTypeOptions = list;
          this.appcatesortList = [
            {
              categoryId: "11",
              label: "我的应用",
              sortNum: 11
            },
            {
              categoryId: "0",
              label: "最近访问",
              sortNum: 0
            },
            ...list
          ];
          this.allAppList = [];
          this.appcatesortList.map(req => {
            this.allAppList.push({ ...req, list: [] });
          });
          this.getAllAppList();
        }
      });
    },
    getAppCatesortList() {
      this.axiosApi("/openapi-uc/appcatesort/list", {}).then(res => {
        if (res.pageInfo.list && res.pageInfo.list.length >= 1) {
          const list = res.pageInfo.list;
          list.map(res => {
            const index = this.osTypeOptions.findIndex(reqs => {
              return reqs.value === res.categoryId;
            });
            if (index >= 0) res.label = this.osTypeOptions[index].label;
          });
          this.appcatesortList = [
            {
              categoryId: "11",
              label: "我的应用",
              sortNum: 11
            },
            {
              categoryId: "0",
              label: "最近访问",
              sortNum: 0
            },
            ...res.pageInfo.list
          ];
          this.allAppList = [];
          this.appcatesortList.map(req => {
            this.allAppList.push({ ...req, list: [] });
          });
          this.getAllAppList();
        }
      });
    },
    handleClose(item) {
      const vm = this;
      vm.dialogVisible = false;
      const url = vm.currentApp.url || vm.currentApp.domain || vm.currentApp.h5Domain;
      if (item === "toApp") {
        openApp(url, { authAppId: vm.currentApp.appId }, "_blank");
      }
      const temp = setTimeout(() => {
        vm.otherAppName = "";
        vm.otherAppPath = "";
        vm.innerText = "";
        vm.currentApp = {};
        clearTimeout(temp);
      }, 300);
    },
    isHttpReq (url) {
      if (url) {
        if (url.indexOf("https://") !== -1 || url.indexOf("http://") !== -1 || url.startsWith("/")) {
          return true;
        }
      }
      return false;
    },
    appEnter(app, appList) {
      if (this.btnEditeStatus) return;
      const vm = this;
      // 区分当前应用是否为第三方，只有第三方应用才会弹窗（目前以名称过滤掉）
      // || app.callbackUrl
      let url = app.url || app.domain || app.h5Domain;
      if (!url || url.length < 1) {
        window.$ui.msg({
          type: "info",
          message: "该应用不可打开"
        });
        return;
      }
      if (!this.isHttpReq(url)) {
        url = "//" + url;
      }
      let isOtherApp = false;
      if (url.indexOf(window.location.hostname) < 0) {
        // 取配置项中的全部配置应用
        isOtherApp = true;
      }

      if (vm.tipThirdPartyApp && isOtherApp) {
        vm.currentApp = app;
        vm.otherAppPath = app.url || app.domain || app.h5Domain;
        vm.otherAppName = app.name || app.appName;
        vm.innerText = app.inner || app.contactInfo;
        vm.dialogVisible = true;
      } else {
        if (url) {
          const relayHref = url;
          openApp(relayHref, { authAppId: app.appId }, "_blank");
        }
      }
    },
    handleDownload (val) {
      const vm = this;
      // this.$refs.popperOptions.forEach(e => {
      //   e.doClose()
      // })
      vm.appDownload = Object.assign(
        {},
        {
          windowsX64downloadUrl: "",
          windowsX32downloadUrl: "",
          windowsXAlldownloadUrl: "",
          macAppdownloadUrl: "",
          linuxAppdownloadUrl: "",
          androidAppdownloadUrl: "",
          iosAppdownloadUrl: ""
        }
      );
      const gateway = window.$app.gateway;
      vm.axiosApi(`/openapi-uc/app/${val}`, "", "get").then(res => {
        // 1-web；2-android；3-ios；4-pc；5-服务；6-跨端应用(WindowsX86); 7-跨端应用(WindowsARM); 8-跨端应用(MacX86); 9-跨端应用(MacARM); 10-小程序(微信);
        // 11-小程序(钉钉); 0-其他。21-跨端应用(Windows 64); 22-跨端应用(Windows 32); 23-跨端应用(Windows 兼容); 24-跨端应用(mac); 25-跨端应用(linux);
        if (res.responseEntity && res.responseEntity.appModuleList) {
          const list = res.responseEntity.appModuleList;
          list.forEach(item => {
            if (item.moduleType === "21" && item.downloadUrl) {
              vm.appDownload.windowsX64downloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "22" && item.downloadUrl) {
              vm.appDownload.windowsX32downloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "23" && item.downloadUrl) {
              vm.appDownload.windowsXAlldownloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "24" && item.downloadUrl) {
              vm.appDownload.macAppdownloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "25" && item.downloadUrl) {
              vm.appDownload.linuxAppdownloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "2" && item.downloadUrl) {
              // 安卓下载
              vm.appDownload.androidAppdownloadUrl = gateway + "/fs/media" + item.downloadUrl;
            }
            if (item.moduleType === "1" && item.downloadUrl) {
              // ios跳转
              vm.appDownload.iosAppdownloadUrl = item.downloadUrl;
            }
          });
          if (
            vm.appDownload.windowsX64downloadUrl ||
            vm.appDownload.windowsX32downloadUrl ||
            vm.appDownload.windowsXAlldownloadUrl ||
            vm.appDownload.macAppdownloadUrl ||
            vm.appDownload.linuxAppdownloadUrl ||
            vm.appDownload.androidAppdownloadUrl ||
            vm.appDownload.iosAppdownloadUrl
          ) {
            vm.isShowDownload = true;
          } else {
            vm.isShowDownload = false;
          }
        }
      });
    },
    downloadFile(fileName, content, target = false) {
      let elemIF = document.createElement("iframe");
      elemIF.src = content;
      elemIF.download = fileName + content.substring(content.lastIndexOf("."));
      elemIF.style.display = "none";
      target && (elemIF.target = target);
      document.body.appendChild(elemIF);
      const temp = setTimeout(() => {
        document.body.removeChild(elemIF);
        clearTimeout(temp);
      }, 500);
    },
    changeAppList(id, index) {
      const boxId = document.querySelectorAll(`#${id}`);
      this.activeIndex = index;
      if (boxId.length >= 1) {
        let step = boxId[0].offsetTop <= 0 ? 0 : boxId[0].offsetTop - this.scrollHeight;
        if (id === "tw-ecoapplist11") {
          step = 0;
        }
        window.scrollTo(0, step);
      }
    },
    setAppList(item) {
      const flag = this.appList.some(x => {
        return x.appId === item.id;
      });
      return !flag;
    },

    editMyApp(type, item) {
      if (type === "1") {
        // 添加
        if (this.appList.length > this.collect_app_max_count * 1 - 1) {
          window.$ui.msg({
            type: "info",
            message: "已经超过我的应用最大数量，无法添加"
          });
          return;
        }
        const flag = this.appList.some(x => {
          return x.appId === item.id;
        });
        if (flag) {
          window.$ui.msg({
            type: "info",
            message: "重复添加应用"
          });
        } else {
          const obj = {
            appInfo: item,
            appId: item.id,
            userId: window.$app.user.userId,
            sortNo: this.appList.length + 1
          };
          this.appList.push(obj);
        }
      } else {
        // 删除
        const index = this.appList.findIndex(x => {
          return x.appId === item;
        });
        this.delAppList.push(this.appList[index].appId);
        this.appList.splice(index, 1);
      }
    },

    deletcollection(appids) {
      this.axiosApi(
        "/openapi-uc/app/v2/deletcollection",
        {
          userId: window.$app.user.userId,
          appids
        },
        "post"
      ).then(res => {
        if (res.serverResult.resultCode === "200") {
          window.$ui.msg({
            type: "success",
            message: "保存成功"
          });
          this.btnEditeStatus = false;
          this.getcollection();
        } else {
          window.$ui.msg({
            type: "error",
            message: "保存失败"
          });
        }
      });
    },

    getcollection() {
      this.axiosApi(
        "/openapi-uc/app/v2/getcollection",
        {
          userId: window.$app.user.userId,
          appTerminal: "1",
          displayPlatformFilter: this.displayPlatformFilter
        },
        "post"
      )
        .then(res => {
          if (res.pageInfo && res.pageInfo.list && res.pageInfo.list.length >= 1) {
            const list = res.pageInfo.list;
            this.appList = list;
            this.btnEditeStatus = false;
          } else {
            this.appList = [];
          }
        })
        .catch(err => {
          this.appList = [];
          console.log(err);
        });
    },
    // 取消保存
    canelSave() {
      this.appList = this.appListCopy;
      this.btnEditeStatus = false;
    },
    editeMyApp() {
      if (this.btnEditeStatus) {
        if (this.appList.length < 1 && this.delAppList.length >= 1) {
          this.deletcollection(this.delAppList);
        } else if (this.appList.length >= 1) {
          const appCollections = this.appList.map(req => {
            return {
              appId: req.appId,
              userId: window.$app.user.userId,
              sortNo: req.sortNo
            };
          });

          this.axiosApi("/openapi-uc/app/v2/collection", { appCollections }, "post").then(res => {
            if (res.serverResult.resultCode === "200") {
              window.$ui.msg({
                type: "success",
                message: "保存成功"
              });
              this.getcollection();
            } else {
              window.$ui.msg({
                type: "error",
                message: "保存失败"
              });
            }
          });
        } else {
          this.btnEditeStatus = false;
        }
      } else {
        this.btnEditeStatus = true;
        this.appListCopy = this.deepClone(this.appList);
      }
    },

    async getAllAppList(appName) {
      if (!this.preventReClick) return;
      this.preventReClick = false;
      this.allAppList.forEach(f => {
        f.list = [];
      });
      const parmas = {
        appName,
        appTerminal: "1",
        userId: window.$app.user.userId,
        displayPlatformFilter: this.displayPlatformFilter,
        startTime: "1999-01-01 00:00:00"
      };
      const parmas1 = {
        userId: window.$app.user.userId,
        appName,
        mateRoleType: "1",
        managerStatus: "1",
        appTerminal: "1",
        displayPlatformFilter: this.displayPlatformFilter
      };
      const data = await this.axiosApiAll(
        [
          { url: "/openapi-uc/app/getAppRecentVisit", parmas },
          { url: "/openapi-uc/app/auth/list", parmas: parmas1 }
        ],
        "post"
      );
      this.getAppRecentVisit(data[0], appName);
      const res = data[1];
      if (res.pageInfo.list && res.pageInfo.list.length >= 1) {
        this.authList = res.pageInfo.list;
        this.allAppList[1].list = this.appRecentVisit;
        this.authList.forEach(req => {
          this.allAppList.forEach(reqs => {
            if (req.type === reqs.categoryId) {
              // || req.callbackUrl
              reqs.list.push({
                id: req.id,
                appId: req.appId,
                appName: req.appName,
                name: req.appName,
                url: req.domain || req.h5Domain || req.callbackurl,
                addAccreditCode: true,
                img: req.icon1 ? `${window.$app.fsBaseUrl || window.$app.gateway}/fs/media${req.icon1}` : "",
                hasFile: req.hasFile,
                inner: (req.inner && req.inner.replace(/\n/g, "<br />")) || ""
              });
            }
          });
        });
        this.groupAppList = this.allAppList.filter((x, i) => {
          return x.list.length >= 1;
        });
        if (!appName) {
          this.appcatesortList = this.appcatesortList.filter(y => {
            return (
              this.groupAppList.findIndex(g => {
                return g.categoryId === y.categoryId;
              }) >= 0 || y.categoryId === "11"
            );
          });
          this.showappcate = true;
        }
      } else {
        this.allAppList[1].list = this.appRecentVisit;
        this.groupAppList = [];
      }
      this.appList_show = true;
      const temp = setTimeout(() => {
        this.preventReClick = true;
        clearTimeout(temp);
      }, this.appTime);
    },
    getMobileAppList(appName) {
      const params = {
        userId: window.$app.user.userId,
        appName,
        mateRoleType: "1",
        managerStatus: "1",
        appTerminal: "1",
        displayPlatformFilter: this.displayPlatformFilter
      };
      this.axiosApi("/openapi-uc/app/auth/list", params, "post")
        .then(res => {
          if (res.pageInfo.list && res.pageInfo.list.length >= 1) {
            // this.authList = res.pageInfo.list
            let list = res.pageInfo.list;
            this.authList = list.map(req => {
              return {
                id: req.id,
                appId: req.appId,
                appName: req.appName,
                name: req.appName,
                url: req.domain || req.h5Domain || req.callbackurl,
                img: req.icon1 ? `${window.$app.fsBaseUrl || window.$app.gateway}/fs/media${req.icon1}` : "",
                inner: (req.inner && req.inner.replace(/\n/g, "<br />")) || ""
              };
            });
            console.log(this.authList, list);
          }
        })
        .catch(err => {
          console.log(err);
          this.paasName = this.webName;
        });
    },

    /**
     * @description: 获取最近访问应用
     * @param {*}
     * @return {*}
     */
    getAppRecentVisit(res, appName) {
      if (appName) {
        this.appRecentVisit = this.appRecentVisit.filter(y => {
          return y.name.indexOf(appName) >= 0;
        });
        return;
      }

      if (res.pageInfo && res.pageInfo.list && res.pageInfo.list.length >= 1) {
        this.appRecentVisit = res.pageInfo.list.map(x => {
          // || x.callbackUrl
          return {
            ...x,
            img: x.icon1 ? `${window.$app.fsBaseUrl || window.$app.gateway}/fs/media${x.icon1}` : "",
            id: x.id,
            appId: x.appId,
            name: x.appName,
            url: x.domain || x.h5Domain || x.callbackurl,
            hasFile: x.hasFile,
            inner: (x.contactInfo && x.contactInfo.replace(/\n/g, "<br />")) || ""
          };
        });
      } else {
        this.appRecentVisit = [];
      }
    },
    axiosApiAll(arr = [], type = "post") {
      return new Promise((resolve, reject) => {
        let requestPromiseArray = [];
        const axios = axios;
        arr.forEach(item => {
          const request = axios[type](`${window.$app.gateway}${item.url}`, item.parmas).then(res => res);
          requestPromiseArray.push(request);
        });
        Promise.all(requestPromiseArray)
          .then(responseList => {
            resolve(responseList);
          })
          .catch(err => {
            reject(err);
            console.log(err);
          });
      });
    },

    async axiosApi(url, parmas = {}, type = "post", headers) {
      let resq;
      try {
        resq = await axios[type](`${window.$app.gateway}${url}`, parmas, headers);
      } catch (error) {
        console.log("error", error);
        resq = "";
      }
      if (resq && resq.serverResult.resultCode === "200") {
        return resq;
      } else {
        window.$ui.msg({
          message: resq.serverResult.resultMessage,
          type: "error"
        });
      }
    },
    // 开始拖拽事件
    onStart() {
      this.drag = true;
    },
    // 拖拽结束事件
    onEnd() {
      this.drag = false;
      this.appList.forEach((res, inx) => {
        res.sortNo = inx + 1;
      });
    },

    getPaasName() {
      const params = {
        singleTable: "true",
        conditions: [
          {
            fieldName: "key",
            fieldValues: ["paas_platform_name"],
            operator: "FUZZY_MATCH",
            prepender: "AND"
          },
          {
            fieldName: "status",
            fieldValues: ["1"],
            operator: "EQUAL",
            prepender: "AND"
          }
        ],
        pagination: { numPerPage: 10, pageNo: 1 }
      };

      this.axiosApi("/openapi-uc/sys/config/search", params, "post")
        .then(res => {
          if (res.pageInfo && res.pageInfo.list && res.pageInfo.list.length >= 1) {
            this.paasName = res.pageInfo.list[0].value;
          } else {
            this.paasName = this.webName;
          }
        })
        .catch(err => {
          console.log(err);
          this.paasName = this.webName;
        });
    },
    getAppMaxCount() {
      const params = {
        singleTable: "true",
        conditions: [
          {
            fieldName: "key",
            fieldValues: ["collect_app_max_count"],
            operator: "FUZZY_MATCH",
            prepender: "AND"
          },
          {
            fieldName: "status",
            fieldValues: ["1"],
            operator: "EQUAL",
            prepender: "AND"
          }
        ],
        pagination: { numPerPage: 10, pageNo: 1 }
      };

      this.axiosApi("/openapi-uc/sys/config/search", params, "post").then(res => {
        if (res.pageInfo && res.pageInfo.list && res.pageInfo.list.length >= 1) {
          this.collect_app_max_count = res.pageInfo.list[0].value;
        } else {
          this.collect_app_max_count = 10;
        }
      });
    },

    // 详情
    async getAppDetails(appId) {
      const vm = this;
      await this.getSections();
      await this.getSubject();
      vm.commentAdd.appComment = "";
      vm.commentAdd.score = 0;
      this.axiosApi("/openapi-uc/app/" + appId, "", "get").then(response => {
        vm.appInfo = response.responseEntity;
        // console.log((dd.style.display = 'none'))
        vm.showEwm();
        window.scrollTo(0, 0);
        vm.fetchCommentShow();
        vm.fetchData();
        vm.queryDocMenuById();
      });
    },
    async getSections() {
      const getDictItemUrl = "/openapi-base/base/queryDictItemList";
      const sectionDictItemReq = {
        dictTypeId: "SCHOOL_SECTION",
        orderMethods: [
          {
            field: "sortNo",
            method: "ASC"
          }
        ]
      };
      // 学段

      await this.axiosApi(getDictItemUrl, sectionDictItemReq, "post").then(response => {
        this.sectionList = response.pageInfo.list;
      });
    },
    async getSubject() {
      const getDictItemUrl = "/openapi-base/base/queryDictItemList";
      const sectionDictItemReq = {
        dictTypeId: "SUBJECT",
        schoolSection: "SCHOOL_SECTION",
        orderMethods: [
          {
            field: "sortNo",
            method: "ASC"
          }
        ]
      };
      await this.axiosApi(getDictItemUrl, sectionDictItemReq, "post").then(response => {
        this.subjectList = response.pageInfo.list;
      });
    },
    formatSubject(str) {
      // 适用学科
      const vm = this;
      if (!str) return "不限定";
      if (!this.subjectList) return "不限定";
      const list = this.subjectList.filter((v, i) => {
        return str.indexOf(v.dictId) >= 0;
      });
      const list2 = this.sectionList.filter((v, i) => {
        return str.indexOf(v.dictId) >= 0;
      });
      let temp = [];
      if (list.length >= 1) {
        temp = list.map((v, i) => {
          let section;
          vm.sectionList &&
            vm.sectionList.map(s => {
              if (s.dictId === v.parentDictId) {
                section = s.dictName;
              }
            });
          return section + v.dictName;
        });
      }
      if (list2.length >= 1) {
        list2.map(v => {
          temp.push(v.dictName);
        });
      }
      return temp.length >= 1 ? temp.join(",") : "不限定";
    },
    formatSection(str) {
      if (!this.sectionList) return false;
      if (!str) return "不限定";
      if (str === "不限定") return "不限定";
      const list = this.sectionList.filter((v, i) => {
        return str.indexOf(v.dictId) >= 0;
      });
      const temp = list.map(v => {
        return v.remark;
      });
      return temp.length >= 1 ? temp.join(",") : "不限定";
    },
    getOsTypeOptions(value) {
      if (this.osTypeOptions.length < 1 || !value) {
        return "";
      }
      const index = this.osTypeOptions.findIndex(v => {
        return v.value === value;
      });
      return this.osTypeOptions[index].label;
    },
    async convertUrlToQRCode(url) {
      try {
        const res = await QRCode.toDataURL(url)
        this.qrPath = res
      } catch (err) {
        console.log(err)
      }
    },
    showEwm (type) {
      // console.log(window.$app.user)
      let vm = this;
      vm.isPath = true;
      // if (type === "1") {
      //   this.$refs.qrCodeDiv.innerHTML = "";
      // }
      if (
        window.$app.user.token &&
        undefined !== window.$app.user.token &&
        window.$app.user.token !== null &&
        window.$app.user.token !== "null"
      ) {
        //  已登录
        const req = {
          accessToken: window.$app.user.token,
          userId: window.$app.user.userId,
          appCode: this.appInfo.appCode,
          authAppId: this.appInfo.appId
        };
        vm.axiosApi("/openapi-uc/accreditcode/getAccreditCode", req, "post")
          .then(function (response) {
            let token = window.$app.user.token;
            let path = vm.appInfo.domain;
            const params = {
              authAppId: vm.appInfo.appId
            };
            const responseEntity = response.responseEntity;
            let qrPath =
              path +
              (path.indexOf("?") === -1 ? "?" : "&") +
              "accredit_code=" +
              responseEntity.accreditCode +
              "&access_token=" +
              token +
              "&token=" +
              token +
              (params ? "&" + window.$ui.qs.stringify(params) : "");
            vm.convertUrlToQRCode(qrPath)
            console.log(path);
            // eslint-disable-next-line no-new
            // new QRCode(vm.$refs.qrCodeDiv, {
            //   text: vm.qrPath,
            //   width: 150,
            //   height: 150,
            //   colorDark: "#333333", // 二维码颜色
            //   colorLight: "#ffffff", // 二维码背景色
            //   correctLevel: QRCode.CorrectLevel.L // 容错率，L/M/H
            // });
          })
          .catch(function (error) {
            vm.isPath = false;
            console.log(error);
          });
      } else {
        vm.isPath = false;
      }
    },
    commentHandAdd() {
      // 发表评论
      const vm = this;
      vm.commentAdd.appId = vm.appInfo.id;
      vm.commentAdd.userId = window.$app.user.userId;

      if (!vm.commentAdd.appComment) {
        window.$ui.msg({
          message: "评论不能为空",
          type: "info"
        });
        return;
      }
      if (!vm.commentAdd.score) {
        window.$ui.msg({
          message: "评分不能为空",
          type: "info"
        });
        return;
      }

      vm.axiosApi("/openapi-uc/app/comment/add", vm.commentAdd, "post").then(function (response) {
        if (response.serverResult && response.serverResult.resultCode === "200") {
          window.$ui.msg({
            message: "评论成功",
            type: "success"
          });
          vm.commentAdd.appComment = "";
          vm.commentAdd.score = 0;
          vm.fetchData();
          vm.fetchCommentShow();
        }
      });
    },
    fetchCommentShow () {
      const vm = this;
      vm.commentAdd.appId = vm.appInfo.id;
      vm.commentAdd.userId = window.$app.user.userId;
      if (vm.commentAdd.userId) {
        const entity = {
          userId: vm.commentAdd.userId,
          appId: vm.commentAdd.appId
        };
        vm.axiosApi("/openapi-uc/app/comment/getByEntity", entity, "post")
          .then(function (response) {
            if (response.responseEntity) {
              // 已评论不允许再评论
              vm.commentShow = false;
            } else {
              vm.commentShow = true;
            }
          })
          .catch(function (error) {
            window.$ui.msg({
              message: error.serverResult.resultMessage,
              type: "error"
            });
            console.log(error);
          });
      } else {
        // 未登录不允许评论
        vm.commentShow = false;
      }
    },
    fetchData () {
      const vm = this;
      // vm.pageNo++
      vm.comments = [];
      const req = {
        scope: "0",
        appId: vm.appId,
        pageNo: 1,
        numPerPage: 9999
      };
      vm.axiosApi("/openapi-uc/app/comment/joinSearch", req, "post")
        .then(function (response) {
          vm.total = response.pageInfo.total;
          if (response.pageInfo.list && response.pageInfo.list.length > 0) {
            vm.comments = response.pageInfo.list;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    queryDocMenuById() {
      const vm = this;
      const req = { lang: "zh_CN", appId: vm.appInfo.appId };

      vm.axiosApi("/openapi-uc/docMenu/queryDocMenuById/", req, "post").then(function (response) {
        vm.isDocMenu = response.pageInfo && response.pageInfo.list.length >= 1;
      });
    },
    toDocument() {
      const url = window.$app.ecoWebServer + this.documentUrl + `?appId=${this.appInfo.appId}&appType=${this.appInfo.type}`;
      // openApp(url)
      openApp(url, { authAppId: this.appInfo.appId }, "_blank");
    }
  }
};
</script>

<style lang="scss">
@use "./css/index.scss";

// @use "./css/mobile.scss";
// @use "./css/theme.scss";
</style>
